package com.qdsg.ysg.doctor.ui.activity.prescription;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.eventbus.PrescriptionAchieveEvent;
import com.qdsg.ysg.doctor.ui.dialog.UpdateDialog;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.BaseResponse;
import com.rest.response.PrescriptionListResponse;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UtilList;

/**
 * 处方列表界面
 *
 * @author DELL
 * @time 2020/12/2 13:54
 */

public class PrescriptionListActivity extends BaseActivity {
    List<PrescriptionListResponse.pInfo> list = new ArrayList<>();
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_add_pre)
    TextView tvAddPre;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;

    String diagnoseId, preAppend, diagnoseResult, icd;
    MyAdapter adapter;

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_chufang_list;
    }

    @Override
    protected void initViews() {
        EventBus.getDefault().register(this);

        tvTitle.setText("开处方");
//        btnAdd.setVisibility( View.VISIBLE );
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);

        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> queryPrescriptionList());
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {

        });
    }

    @Override
    protected void initData() {
        diagnoseId = getIntent().getStringExtra("diagnoseId");

    }

    @Override
    protected void onResume() {
        super.onResume();
        queryPrescriptionList();
    }


    @SuppressLint("NonConstantResourceId")
    @OnClick({R.id.btn_back, R.id.tv_add_pre})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                setResult(RESULT_OK);
                finish();
                break;
            case R.id.tv_add_pre:
                Bundle bundle = new Bundle();
                bundle.putString("diagnoseId", diagnoseId);
                bundle.putString("icd", icd);
                startActivityForResult(AddPrescriptionActivity.class, bundle, 10001);
                break;
            default:
                break;
        }
    }

    //查看处方详情
    private void queryPrescriptionList() {
        RestProxy.getInstance().queryPrescriptionList(diagnoseId, new Observer<PrescriptionListResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(PrescriptionListResponse prescriptionResponse) {
                if (prescriptionResponse.data.diagInfo != null) {
                    diagnoseResult = prescriptionResponse.data.diagInfo.diagnoseResult;
                    icd = prescriptionResponse.data.diagInfo.icd;
                    preAppend = prescriptionResponse.data.diagInfo.preAppend;
                }

                if (!UtilList.isEmpty(prescriptionResponse.data.pInfo)) {
                    refreshLayout.setVisibility(View.VISIBLE);
                    list.clear();
                    list.addAll(prescriptionResponse.data.pInfo);
                    adapter.notifyDataSetChanged();
                } else {
                    refreshLayout.setVisibility(View.GONE);
                }
                refreshLayout.finishRefresh(true);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }

    //删除已撤销处方

    private void delPrescription(String prescriptionId) {
        RestProxy.getInstance().delPrescription(prescriptionId, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseResponse prescriptionResponse) {
                queryPrescriptionList();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        //data的返回值根据
        switch (requestCode) {
            case 10000:
            case 10001:
                queryPrescriptionList();
//                BaseApplication.prescriptionHashMap.remove( diagnoseId );
                break;
            default:
                break;
        }
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(mContext).inflate(R.layout.item_prescription_list, parent, false));
            return myHolder;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putString("diagnoseId", list.get(position).diagnoseId);
                bundle.putString("prescriptionId", list.get(position).prescriptionId);
                startActivityForResult(PrescriptionBackActivity.class, bundle, 10000);
            });
            holder.btn_confirm.setOnClickListener(v -> {
                UpdateDialog mUpdateDialog = UpdateDialog.newInstance(5, true);
                mUpdateDialog.show(getSupportFragmentManager(), "mUpdateDialog");
                mUpdateDialog.setmListener(new UpdateDialog.OnItemClickListener() {

                    @Override
                    public void onConfirm() {

                        delPrescription(list.get(position).prescriptionId);
                    }

                    @Override
                    public void onCancel() {

                    }
                });

            });
            holder.tv_name.setText("处方" + (position + 1));
            int flag = list.get(position).flag;
            if (flag == 0) {//待审核，可撤销
                holder.tv_status.setText("待审核(可撤销)");
                holder.tv_status.setTextColor(ContextCompat.getColor(mContext, R.color.mainGreen));
            } else if (flag == 1) {
                holder.tv_status.setText("审核通过，待确认(可撤销)");
                holder.tv_status.setTextColor(ContextCompat.getColor(mContext, R.color.mainGreen));
            } else if (flag == 2) {
                holder.tv_status.setText("审核驳回(可撤销)");
                holder.tv_status.setTextColor(ContextCompat.getColor(mContext, R.color.mainGreen));
            } else if (flag == 3) {
                holder.tv_status.setText("患者已确认(不可撤销)");
                holder.tv_status.setTextColor(ContextCompat.getColor(mContext, R.color.commonGrey));
            } else if (flag == 4) {
                holder.tv_status.setText("已撤销");
                holder.tv_status.setTextColor(ContextCompat.getColor(mContext, R.color.commonGrey));
                holder.btn_confirm.setVisibility(View.VISIBLE);
            }
            if (flag == 4) {
                holder.btn_confirm.setVisibility(View.VISIBLE);
            } else {
                holder.btn_confirm.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, btn_confirm, tv_status;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_status = itemView.findViewById(R.id.tv_status);
                btn_confirm = itemView.findViewById(R.id.btn_confirm);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        setResult(RESULT_OK);
        finish();
        return super.onKeyDown(keyCode, event);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PrescriptionAchieveEvent event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
